// model/user.js

// 范例结构
// {
//   "id": 14,
//   "openid": "oLxUE7ZXzOUp8rh2jSLPYxbHKJI0",
//   "username": "汤佳奇",
//   "password": null,
//   "phone": "18516098096",
//   "role": "MEMBER",
//   "parentId": 7,
//   "areaId": null,
//   "inviteCode": null,
//   "bundleId": null,
//   "createdAt": "2024-12-26T08:56:59.571Z",
//   "updatedAt": "2024-12-26T08:59:52.152Z",
//   "children": [],
//   "address": [
//     {
//       "id": 5,
//       "userId": 14,
//       "addressLine1": "1",
//       "addressLine2": null,
//       "city": "北京市",
//       "state": "北京",
//       "district": "1",
//       "postalCode": "1",
//       "country": "1",
//       "receiverName": "汤佳奇",
//       "phoneNumber": "17377317391",
//       "isDefault": true,
//       "createdAt": "2024-12-26T17:42:00.541Z",
//       "updatedAt": "2024-12-26T17:42:00.541Z"
//     }
//   ],
//   "area": null,
//   "applyCabinetOwnerApplications": [
//     {
//       "id": 6,
//       "cabinetBundleId": 4,
//       "userId": 14,
//       "deposit": 0.01,
//       "status": "PENDING",
//       "approvedBy": 4,
//       "createdAt": "2024-12-27T05:05:54.279Z",
//       "updatedAt": "2024-12-28T05:28:41.980Z",
//       "qrCodeUrl": "https://7769-wine-cloud-5ga3lhn38c71a40f-1327788173.tcb.qcloud.la/qrcodes/cabinet_14_1735363720741.png",
//       "channelOrderId": "WX173527595427779QV",
//       "cabinetObjId": "JG-AAAAA",
//       "shippingCode": null,
//       "areaAgentId": 0
//     }
//   ],
//   "approveCabinetOwnerApplications": [],
//   "bundle": null,
//   "cabinetOwnerApplication": {
//     "id": 6,
//     "channelOrderId": "WX173527595427779QV",
//     "cabinetObjId": "JG-AAAAA",
//     "applyStatus": "PENDING",
//     "applyTime": "2024-12-27T05:05:54.279Z",
//     "applyChangeTime": "2024-12-28T05:28:41.980Z",
//     "qrCode": "https://7769-wine-cloud-5ga3lhn38c71a40f-1327788173.tcb.qcloud.la/qrcodes/cabinet_14_1735363720741.png"
//   }
// }
const app = getApp();

const user = {
  token: '', // 用户登录的 JWT Token
  info: {}, // 用户信息对象
  isDirty: false
};

// 设置用户数据
function setUserToken({ token }) {
  user.token = token;
  try {
    wx.setStorageSync('userToken', token);
  } catch (e) {
    console.error('Failed to set userToken in storage:', e);
  }
}

// 获取用户数据
function getUserToken() {
  if (user.token) {
    return user.token;
  }
  try {
    const token = wx.getStorageSync('userToken');
    if (token) {
      user.token = token;
      return token;
    }
  } catch (e) {
    console.error('Failed to get userToken from storage:', e);
  }
  return '';
}

// 设置用户数据
function setUserData({ token, userInfo }) {
  user.token = token;
  user.info = userInfo;
  user.isDirty = false;
  
  try {
    wx.setStorageSync('userToken', token);
    wx.setStorageSync('userInfo', userInfo);
  } catch (e) {
    console.error('Failed to set user data in storage:', e);
  }
}

// 获取用户数据
function getUserData() {
  if (!user.isDirty && user.token && user.info.id) {
    return user; // 优先从内存中获取
  }
  try {
    const token = wx.getStorageSync('userToken');
    const userInfo = wx.getStorageSync('userInfo');
    if (token) user.token = token;
    if (userInfo) user.info = userInfo;
    user.isDirty = false; // 数据已刷新
  } catch (e) {
    console.error('Failed to get user data from storage:', e);
  }
  return user; 
}

// 标记用户数据为脏数据，需要重新获取
function markUserDataDirty() {
  user.isDirty = true;
}

// 清除用户数据（用于注销等场景）
function clearUserData() {
  user.token = '';
  user.info = {};
  user.isDirty = true;
  try {
    wx.removeStorageSync('userToken');
    wx.removeStorageSync('userInfo');
  } catch (e) {
    console.error('Failed to clear user data from storage:', e);
  }
}

module.exports = {
  setUserData,
  getUserData,
  clearUserData,
  setUserToken,
  getUserToken,
  markUserDataDirty,
};